package com.vipheyue.educationmp4.TabFragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;
import com.vipheyue.educationmp4.R;
import com.vipheyue.educationmp4.activity.CourseDisplayActivity;
import com.vipheyue.educationmp4.bean.CourseBean;
import com.vipheyue.educationmp4.bean.GradeBean;
import com.vipheyue.educationmp4.download.DownloadActivity;
import com.vipheyue.educationmp4.download.DownloadInfo;
import com.vipheyue.educationmp4.download.DownloadManager;
import com.vipheyue.fastlib.adapter.BaseRecyclerAdapter;
import com.vipheyue.fastlib.adapter.BaseRecyclerViewHolder;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.FindListener;

import static com.vipheyue.educationmp4.download.DownloadState.FINISHED;


@SuppressLint("ValidFragment")
public class CardFragment extends Fragment {
    private String objId;
    private String title;
    @Bind(R.id.recycler)
    RecyclerView recyclerView;
    ArrayList<CourseBean> mdata = new ArrayList<>();
    private BaseRecyclerAdapter adapter;

    public static CardFragment getInstance(String objId, String title) {
        CardFragment sf = new CardFragment();
        sf.objId = objId;
        sf.title = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_simple_card, null);
        ButterKnife.bind(this, v);
        initData();
        return v;
    }

    private void initData() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);//设置显示方式
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())//第三
//                .drawable(R.drawable.sample)///图片
                .drawable(R.drawable.divider)
                .size(1)
                .build());

        adapter = new BaseRecyclerAdapter<CourseBean>(getActivity(), mdata, R.layout.fragment_detail_item) {
            @Override
            public void init(BaseRecyclerViewHolder holder, CourseBean bean, int position) {
                holder.setText(R.id.tv_item, bean.getCourseName());
                if (bean.getSaved()) {
                    holder.getView(R.id.iv_down).setBackgroundResource(R.drawable.ic_play);
                }else {
                    holder.getView(R.id.iv_down).setBackgroundResource(R.drawable.ic_down);
                }
                holder.getView(R.id.iv_down).setOnClickListener(v -> {
                    if (TextUtils.isEmpty(bean.getUri())) {
                        Toast.makeText(getActivity(), "没有对应视频,请联系管理员", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (bean.getSaved()) {
                        DownloadInfo downloadInfo= DownloadManager.getInstance().querySaved(bean.getBeanSavePath());
                        Intent intent = new Intent(getActivity(), CourseDisplayActivity.class);
                        intent.putExtra("uri", downloadInfo.getFileSavePath());
                        startActivity(intent);

                    }else {
                        try {
                            DownloadManager.getInstance().startDownload(
                                    bean.getUri(), bean.getCourseName(),
                                   bean.getBeanSavePath(), true, false, null);
                            startActivity(new Intent(getActivity(), DownloadActivity.class));
                        } catch (DbException e) {
                            e.printStackTrace();
                            CrashReport.postCatchedException(e);  // bugly会将这个throwable上报
                        }
                    }


                });
            }
        };
        adapter.setOnItemClickLinster(new BaseRecyclerAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
//                DownloadInfo downloadInfo= DownloadManager.getInstance().querySaved( mdata.get(position).getBeanSavePath());
                if (TextUtils.isEmpty(mdata.get(position).getUri())) {
                    Toast.makeText(getActivity(), "没有对应视频,请联系管理员", Toast.LENGTH_SHORT).show();
                    return;
                }
//                Intent intent = new Intent(getActivity(), CourseDisplayActivity.class);
//                if (downloadInfo!=null&&downloadInfo.getState()==FINISHED) {
//                    intent.putExtra("uri", downloadInfo.getFileSavePath());
//                    Toast.makeText(getActivity(), "本地播放", Toast.LENGTH_SHORT).show();
//                }else{
//                    intent.putExtra("uri",  mdata.get(position).getUri());
//                    Toast.makeText(getActivity(), "在线播放", Toast.LENGTH_SHORT).show();
//                }
//                startActivity(intent);
            }
        });
        recyclerView.setAdapter(adapter);//设置适配器

    }

    private void questdata() {
        BmobQuery<CourseBean> query = new BmobQuery<CourseBean>();
        GradeBean gradeBean = new GradeBean();
        gradeBean.setObjectId(objId);
        query.addWhereEqualTo("gradeBean", new BmobPointer(gradeBean));//注意pointer类型
        query.addWhereEqualTo("round", title);//对应周期
        query.order("index");
        query.findObjects(getActivity(), new FindListener<CourseBean>() {
            @Override
            public void onSuccess(List<CourseBean> list) {
                for (CourseBean courseBean : list) {
                    DownloadInfo downloadInfo= DownloadManager.getInstance().querySaved(courseBean.getBeanSavePath());
                    if (downloadInfo!=null&&downloadInfo.getState()==FINISHED) {
                        Logger.e("  "+downloadInfo.getState());
                        courseBean.setSaved(Boolean.TRUE);
                    }else {
                        courseBean.setSaved(Boolean.FALSE);
                    }
                    mdata.add(courseBean);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mdata.clear();
        adapter.notifyDataSetChanged();
        questdata();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}